<?php
/**
 * Created by PhpStorm.
 * User: yaolei
 * Date: 2017/11/22
 * Time: 13:17
 */

namespace Api\Controller;

use Api\Common\BaseController;
use Api\Model\SysCodeModel;
use Api\Model\UserModel;
use Common\helpers\Helper;
use Exception;

class UserController extends BaseController
{
    /***
     * 重写父类方法
     */
    protected function init(){
        //获取当前action名称
        switch (ACTION_NAME){
            case "login":
                $this->is_login=false;
				
                break;
            case "register":
                $this->is_login=false;
                $this->requestType="post";
                break;
            case "sendcode":
                $this->is_login=false;
                $this->requestType="post";
                break;
            case "find":
                $this->is_login=false;
                $this->requestType="post";
                break;
        }
    }
    public function login(){
        $username=$this->getParams("username",true);
        $password=$this->getParams("password",true);
        $remember=$this->getParams("remember");
        $user=M('user')->where("username='".$username."'")->find();
        if(!empty($user)){
            if($user['password']!=$password){
                $this->response(["code"=>203,"msg"=>"用户名或者密码错误"]);
            }
            if($user['isvalid']==0){
                $this->response(["code"=>203,"msg"=>"该用户已经冻结，请和管理员联系"]);
            }
            M('user')->where("id=".$user['id'])->save([
                'login_time'=>time(),
                'login_count'=>$user['login_count']+1,
                'last_login_time'=>$user['login_time']
            ]);
            //如果是记住密码   7天后过期  否则2小时后过期
            if($remember==1){
                $is_update=0;
                $expires_in=7*84600;
            }else{
                $is_update=1;
                $expires_in=1*1200;
            }
            $duetime=time()+$expires_in;
            $token=$this->getToken();
            M('auth_token')->add([
                'user_id'=>$user['id'],
                'token'=>$token,
                'is_update'=>$is_update,
                'expires_in'=>$expires_in,
                'duetime'=>$duetime,
                'createdtime'=>time()
                ]);
            $this->response(["code"=>SUCCESS_CODE,"data"=>[
                "user_id"=>$user['id'],
                'token'=>$token,
                'username'=>$user['username'],
                'name'=>$user['name'],
                'headpic'=>$user['headpic']
            ],'msg'=>'登录成功！！！']);
        }else{
            $this->response(["code"=>203,"msg"=>"用户名或者密码错误"]);
        }
    }


    public function register(){
        $inviter_id=$this->getParams("inviter_id");
        $username=$this->getParams("username",true);
        $password=$this->getParams("password",true);
        $code=$this->getParams("code",true);
        if(!(Helper::checkMobile($username))) {
           $this->response(['code'=>'203','msg'=>'手机号格式有误']);
        }
        if(!empty($inviter_id)){
            $inviter_user=M('user')->find($inviter_id);
            if(!empty($inviter_user)){
                $count=M('user')->where("username='".$username."' or mobile='".$username."' or email='".$username."'")->count();
                if($count>0){
                    $this->response(['code'=>204,'msg'=>$username.' 已经被注册']);
                }else{
                    //验证短信验证码正确性
                    if(SysCodeModel::checkCode($username,$code)){
                        $user=new UserModel();
                        $user->inviter_id=$inviter_id;
                        $user->code=$code;
                        if($user->data([
                            'username'=>$username,
                            'password'=>$password,
                            'mobile'=>$username,
                            'reg_time'=>time()
                        ])->add()){
                            $this->response(['code'=>SUCCESS_CODE,'msg'=>'注册成功']);
                        }else{
                            $this->response(['code'=>203,'msg'=>'用户注册失败，请和管理员联系']);
                        }
                    }else{
                        $this->response(['code'=>203,'msg'=>'验证码不存在或者已经过期']);
                    }
                }
            }else{
                $this->response(['code'=>203,'msg'=>'邀请人信息不存在']);
            }
        }else{
            $this->response(['code'=>203,'msg'=>'您不能直接注册，必须要在邀请人链接下才能注册']);
        }
    }

    /***
     * 向用户发送验证码
     */
    public function sendcode(){
        $type=$this->getParams("type");
        $mobile=$this->getParams("mobile",true);
        //注册
        if($type==0){
            if(Helper::checkMobile($mobile)){
                $count=M('user')->where("username='".$mobile."' or mobile='".$mobile."' or email='".$mobile."'")->count();
                if($count>0){
                    $this->response(['code'=>204,'msg'=>$mobile.' 已经使用']);
                }else{
                    $result=SysCodeModel::getCode($mobile);
                    if($result!=false && $result+C("sendNotCode")>time()){
                        $this->response(['code'=>203,'msg'=>'请在'.C("sendNotCode")."秒后重新获取"]);
                    }else{
                        if(SysCodeModel::send($mobile,$type)){
                            $this->response(['code'=>SUCCESS_CODE,'msg'=>'验证码已经发送到您的手机']);
                        }else{
                            $this->response(['code'=>203,'msg'=>'验证码发送失败，请稍后再试']);
                        }
                    }
                }
            }else{
                $this->response(['code'=>203,'msg'=>'手机号格式有误']);
            }
        }elseif($type==1){//登录
			if(Helper::checkMobile($mobile)){
				$result=SysCodeModel::getCode($mobile);
				if($result!=false && $result+C("sendNotCode")>time()){
					$this->response(['code'=>203,'msg'=>'请在'.C("sendNotCode")."秒后重新获取"]);
				}else{
					if(SysCodeModel::send($mobile,$type)){
						$this->response(['code'=>SUCCESS_CODE,'msg'=>'验证码已经发送到您的手机']);
					}else{
						$this->response(['code'=>203,'msg'=>'验证码发送失败，请稍后再试']);
					} 
				}
            }else{
                $this->response(['code'=>203,'msg'=>'手机号格式有误']);
            }
		}elseif($type==2){//找回密码
            $count=M('user')->where("username='".$mobile."' or mobile='".$mobile."' or email='".$mobile."'")->count();
            if($count==0){
                $this->response(['code'=>203,'msg'=>'用户信息未找到']);
            }else{
                if(Helper::checkMobile($mobile)){
                    $result=SysCodeModel::getCode($mobile);
                    if($result!=false && $result+C("sendNotCode")>time()){
                        $this->response(['code'=>203,'msg'=>'请在'.C("sendNotCode")."秒后重新获取"]);
                    }else{
                        if(SysCodeModel::send($mobile,$type)){
                            $this->response(['code'=>SUCCESS_CODE,'msg'=>'验证码已经发送到您的手机']);
                        }else{
                            $this->response(['code'=>203,'msg'=>'验证码发送失败，请稍后再试']);
                        }
                    }
                }else{
                    $this->response(['code'=>203,'msg'=>'手机号格式有误']);
                }
            }
        }else{
            $this->response(['code'=>203,'msg'=>'type数据有误']);
        }
    }

    public function find(){
        $username=$this->getParams("username",true);
        $findcode=$this->getParams("findcode",true);
        $password=$this->getParams("password",true);
        $repassword=$this->getParams("repassword",true);
        if(strlen($password)!=32){
            $this->response(['code'=>203,'msg'=>'密码需要进行加密']);
        }
        if($password!=$repassword){
            $this->response(['code'=>203,'msg'=>'两次输入的密码不一致']);
        }
        if(SysCodeModel::checkCode($username,$findcode)){
            $count=M('user')->where("username='".$username."' or mobile='".$username."' or email='".$username."'")->count();
            if($count==0){
                $this->response(['code'=>203,'msg'=>'用户信息未找到']);
            }else{
                try
                {
                    $is_update=M('user')->where("username='".$username."' or mobile='".$username."' or email='".$username."'")->save([
                        'password'=>$repassword
                    ]);
                    if($is_update){
                        SysCodeModel::deleteCode($username,$findcode);
                        $this->response(['code'=>SUCCESS_CODE,'msg'=>'密码修改成功']);
                    }else{
                        SysCodeModel::deleteCode($username,$findcode);
                        $this->response(['code'=>203,'msg'=>'密码修改失败，待修改的密码可能与原密码一致，请检查']);
                    }
                }
                catch (Exception $e)
                {
                    $this->response(['code'=>203,'msg'=>'保存失败，请和管理员联系']);
                }
            }
        }else{
            $this->response(['code'=>203,'msg'=>'验证码不存在或者已经过期']);
        }
    }
}